package com.app.toolboxlibrary;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class CutDownTimeUtil {

    private CutDownListener cutDownListener;
    private final int cutDownningWhat = 0x01;//计时中发送标志
    private final int cutDownFinishWhat = 0x02;//计时结束标志
    private int time = 0;//计时器计时
    private int finalTime = 10;//总时间
    //配合线程使用
    Handler cutDownHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case cutDownningWhat:
                    if( time < finalTime){
                        time++;
                        getCutDownListener().onCutDownning(time);
                        Message message = this.obtainMessage(cutDownningWhat);
                        this.sendMessageDelayed(message, 1000);
                    }else{
                        cutDownHandler.sendEmptyMessage(cutDownFinishWhat);
                    }

                    break;
                case cutDownFinishWhat:
                    getCutDownListener().onFinish();
                    this.removeMessages(cutDownningWhat);
                    break;
            }
        }
    };

    //初始化
    public CutDownTimeUtil(int allTime) {
        this.finalTime = allTime;
    }

    //启动
    public void startCutDown() {
        cutDownHandler.sendEmptyMessageDelayed(cutDownningWhat,1000);
    }

    //停止
    public void stopcutDown() {
        cutDownHandler.removeMessages(cutDownningWhat);
        cutDownHandler.removeMessages(cutDownFinishWhat);
        cutDownHandler.removeCallbacksAndMessages(null);
    }

    //获取监听事件
    public CutDownListener getCutDownListener() {
        if (null == cutDownListener) {
            cutDownListener = new CutDownListener() {
                @Override
                public void onCutDownning(int executeTime) {

                }

                @Override
                public void onFinish() {

                }
            };
        }
        return cutDownListener;
    }

    //设置回调监听
    public void setCutDownListener(CutDownListener cutDownListener) {
        this.cutDownListener = cutDownListener;
    }

    //回调处理
    public interface CutDownListener {
        /**
         * 已执行的时间
         *
         * @param executeTime 执行时间
         */
        void onCutDownning(int executeTime);

        void onFinish();
    }
}
